package sanphone.com.runningschool.JuShou;


import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

import sanphone.com.runningschool.BaseActivity;
import sanphone.com.runningschool.ForceOffline;
import sanphone.com.runningschool.InterfaceLocation;
import sanphone.com.runningschool.LogIn.LogInActivity;
import sanphone.com.runningschool.R;
import sanphone.com.runningschool.RequestHttp.RequestHttp;
import sanphone.com.runningschool.entity.JuShouInfo;


public class JuShouActivity extends BaseActivity {
    private EditText thingName, thingWeight, thingDescribtion, startaddress, endlocation, money;
    private String nameStr, WeigtStr, DescribtionStr, startDaystr, startHourStr,startMinuteStr, sendDayStr, sendHourStr,sendMinuteStr, startaddressStr, endloactionStr, moneyStr;
    private Button SubmitButton;
    private String id, userName, phone;
    private Spinner start_day;
    private Spinner start_hour;
    private Spinner send_day;
    private Spinner send_hour;
    private int y, m, d, startd = 0, sendD = 0;
    private String startTime, sendTime;
    private Spinner start_minute;
    private Spinner send_minute;
    private SharedPreferences sprf;
    private String NUMBER_EXCATE= "^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jushou);
        sprf=getSharedPreferences("data",MODE_PRIVATE);
        ForceOffline offline=new ForceOffline(sprf.getString("schoolId",null),this);
        offline.check();
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        initView();
        getSpinnerData();
        SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
        id = pref.getString("schoolId", null);
        userName = pref.getString("userName", null);
        phone = pref.getString("userPhone", null);

        SubmitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (startDaystr) {
                    case "今天":
                        startd = d;
                        break;
                    case "明天":
                        startd = d + 1;
                        break;
                    case "后天":
                        startd = d + 2;
                        break;
                    case "大后天":
                        startd = d + 3;
                        break;
                }
                switch (sendDayStr) {
                    case "今天":
                        sendD = d;
                        break;
                    case "明天":
                        sendD = d + 1;
                        break;
                    case "后天":
                        sendD = d + 2;
                        break;
                    case "大后天":
                        sendD = d + 3;
                        break;
                }
               startTime = y + "-" + m + "-" + startd + " " + startHourStr + ":"+startMinuteStr+":00";
                sendTime = y + "-" + m + "-" + sendD + " " + sendHourStr + ":"+sendMinuteStr+":00";
                nameStr = thingName.getText().toString();
                WeigtStr = thingWeight.getText().toString();
                DescribtionStr = thingDescribtion.getText().toString();
                startaddressStr = startaddress.getText().toString();
                endloactionStr = endlocation.getText().toString();
                moneyStr = money.getText().toString();
                if (nameStr.equals("") || WeigtStr.equals("") || DescribtionStr.equals("") ||
                        startaddressStr.equals("") || endloactionStr.equals("") || moneyStr.equals("")) {
                    Toast.makeText(v.getContext(), "请填写完整的信息!", Toast.LENGTH_SHORT).show();
                }else if(!isMatch(NUMBER_EXCATE,WeigtStr)||!isMatch(NUMBER_EXCATE,moneyStr)){
                    Toast.makeText(v.getContext(), "请填写正确形式的信息!", Toast.LENGTH_SHORT).show();
                }
                else if(!isMatch(NUMBER_EXCATE,WeigtStr)&&!isMatch(NUMBER_EXCATE,moneyStr)){
                    Toast.makeText(v.getContext(), "请填写正确形式的信息!", Toast.LENGTH_SHORT).show();
                }
                else {
                    ExecutorService executorService = Executors.newSingleThreadExecutor();
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            JSONObject json = new JSONObject();
                            try {

                                json.put("thingName", nameStr);
                                json.put("thingWeight", Double.parseDouble(WeigtStr));
                                json.put("thingPlace", startaddressStr);
                                json.put("deliverPlace", endloactionStr);
                                json.put("deliverTime", sendTime);
                                json.put("userId", id);
                                json.put("userName", userName);
                                json.put("userPhone", phone);
                                json.put("money", moneyStr);
                                json.put("otherDeatil", DescribtionStr);
                                json.put("thingTime",startTime);
                                RequestHttp requestHttp = new RequestHttp(InterfaceLocation.getLocation() + "sendUserBehavior",JuShouActivity.this);
                                String response = requestHttp.post(json);
                                Log.e("发布举手之劳", response);
                                JSONObject responseJson = new JSONObject(response);
                                if (responseJson.getString("data").equals("发布失败！")) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(JuShouActivity.this, "发布失败", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                } else if (responseJson.getString("data").equals("没有登录或登录已过期")) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(JuShouActivity.this, "没有登录或登录已过期", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    startActivity(new Intent(JuShouActivity.this, LogInActivity.class));
                                } else {
                                    String data = responseJson.getString("data");
                                    Gson gson = new Gson();
                                    final JuShouInfo info = gson.fromJson(data, JuShouInfo.class);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(JuShouActivity.this,"您的信息发布成功!", Toast.LENGTH_SHORT).show();
                                            JuShouActivity.this.finish();
                                        }
                                    });
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        });
    }

    private void getSpinnerData() {
//        ArrayAdapter<String>adapter1=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,day);
//        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        ArrayAdapter<String>adapter2=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,hour);
//        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        start_day.setAdapter(adapter1);
//        start_hour.setAdapter(adapter2);
//        send_day.setAdapter(adapter1);
//        send_hour.setAdapter(adapter2);
        // TODO: 2018/8/2 得到当前系统的时间

        Calendar mCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+8"));
        mCalendar.setTimeInMillis(Calendar.getInstance().getTimeInMillis());
        y = mCalendar.get(Calendar.YEAR);
        m = mCalendar.get(Calendar.MONTH);
        d = mCalendar.get(Calendar.DAY_OF_MONTH);
        Log.d("当前系统时间", y + " " + m + " " + d);

        final String[] day = getResources().getStringArray(R.array.day);
        final String[] hour = getResources().getStringArray(R.array.hour);
        final String[] minute=getResources().getStringArray(R.array.minute);
        start_day.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                startDaystr = day[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                startDaystr = "今天";
            }
        });
        start_hour.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                startHourStr = hour[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                startHourStr = "1:00";
            }
        });
        start_minute.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                startMinuteStr = minute[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                startMinuteStr = "01";
            }
        });

        send_day.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                sendDayStr = day[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                sendDayStr = "今天";
            }
        });
        send_hour.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                sendHourStr = hour[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                sendHourStr = "1:00";
            }
        });
       send_minute.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                sendMinuteStr = minute[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                sendMinuteStr = "01";
            }
        });
    }

    private void initView() {
        thingName = findViewById(R.id.thing);
        thingDescribtion = findViewById(R.id.thing_content);
        thingWeight = findViewById(R.id.thingWeight);
        startaddress = findViewById(R.id.sendlocation_txt);
        endlocation = findViewById(R.id.location_txt);
        SubmitButton = findViewById(R.id.submit);
        money = findViewById(R.id.money_txt);

        start_day = findViewById(R.id.start_day);
        start_hour = findViewById(R.id.start_hour);
        send_day = findViewById(R.id.send_day);
        send_hour = findViewById(R.id.send_hour);
        start_minute =  findViewById(R.id.start_minute);

        send_minute =  findViewById(R.id.send_minuter);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                JuShouActivity.this.finish();
                break;
            default:
                break;
        }
        return true;
    }
    private boolean isMatch(String pe,CharSequence input){
        return input != null && input.length() > 0 && Pattern.matches(pe, input);

    }
}
